/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoanListUI.java
 *
 * Created on 2010.11.09., 13:25:19
 */
package workshopdesign.UI;

import java.util.ArrayList;
import javax.swing.RowFilter;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import workshopdesign.Control.LoanController;
import workshopdesign.Model.Copy;
import workshopdesign.Model.DVD;
import workshopdesign.Model.Loan;
import workshopdesign.Model.Person;

/**
 *
 * @author Dom
 */
public class LoanListUI extends javax.swing.JPanel {

    public enum ListMethod {

        ByPerson, ByDVD, ByCopy, None
    };
    private ListMethod listMethod = ListMethod.None;
    private BaseUIController parent;
    private Person person = null;
    private DVD dvd = null;
    private Copy copy = null;
    private LoanController loanController = LoanController.getLoanController();
    private DefaultTableModel model;
    private TableRowSorter<DefaultTableModel> sorter;
    private TableColumn name_column;

    /** Creates new form LoanListUI */
    public LoanListUI(BaseUIController parent, String title) {
        initComponents();

        this.parent = parent;

        this.setBorder(new TitledBorder(title));

        model = (DefaultTableModel) loan_table.getModel();
        sorter = new TableRowSorter<DefaultTableModel>(model);
        loan_table.setRowSorter(sorter);

        filter_field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                filter_data();
            }
        });

        DefaultTableColumnModel columnModel = new DefaultTableColumnModel();

        name_column = new TableColumn(1, 75);
        name_column.setHeaderValue("Name/Title");
        columnModel.addColumn(name_column);

        TableColumn state_column = new TableColumn(2, 75);
        state_column.setHeaderValue("State");
        columnModel.addColumn(state_column);

        loan_table.setAutoCreateColumnsFromModel(false);
        loan_table.setColumnModel(columnModel);
    }

    private void filter_data() {
        sorter.setRowFilter(RowFilter.regexFilter(".*" + filter_field.getText() + ".*"));
    }

    public DVD getDvd() {
        return dvd;
    }

    public void setDvd(DVD dvd) {
        this.dvd = dvd;
        person = null;
        copy = null;
        listMethod = ListMethod.ByDVD;
        name_column.setHeaderValue("Name");
        load_data();
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
        dvd = null;
        copy = null;
        listMethod = ListMethod.ByPerson;
        name_column.setHeaderValue("Title");
        load_data();
    }

    public Copy getCopy() {
        return copy;
    }

    public void setCopy(Copy copy) {
        this.copy = copy;
        dvd = null;
        person = null;
        listMethod = ListMethod.ByCopy;
        name_column.setHeaderValue("Name");
        load_data();
    }

    public void clear() {
        person = null;
        dvd = null;
        listMethod = ListMethod.None;
        load_data();
        loan_table.clearSelection();
    }

    public void load_data() {
        ArrayList<Loan> loans = null;

        switch (listMethod) {
            case ByDVD:
                if (dvd == null) {
                    clear();
                    return;
                }
                loans = loanController.searchDvd(dvd.getId());
                break;
            case ByPerson:
                if (person == null) {
                    clear();
                    return;
                }
                loans = loanController.searchPerson(person.getId());
                break;
            case ByCopy:
                if (copy == null) {
                    clear();
                    return;
                }
                loans = loanController.searchCopy(copy.getId());
                break;
            case None:
                model.setRowCount(0);
                return;
        }

        loan_table.clearSelection();

        model.setRowCount(loans.size());
        int row = 0;
        for (Loan loan : loans) {

            Person the_person = loanController.getPerson(loan.getId());
            DVD borrowed_dvd = loanController.getDvd(loan.getId());

            model.setValueAt(loan.getId(), row, 0);

            switch (listMethod) {
                case ByDVD:
                case ByCopy:
                    model.setValueAt(the_person.getName(), row, 1);
                    break;
                case ByPerson:
                    model.setValueAt(borrowed_dvd.getTitle(), row, 1);
                    break;
            }

            model.setValueAt(loan.getState().toString(), row, 2);
            model.setValueAt(the_person.getName(), row, 3);
            model.setValueAt(borrowed_dvd.getTitle(), row, 4);
            model.setValueAt(loan.getCopyId(), row, 5);


            row++;
        }
    }

    public Loan get_selected() {
        int selected_row = loan_table.getSelectedRow();

        long loan_id = Long.valueOf((String.valueOf(model.getValueAt(selected_row, 0))));
        return loanController.get(loan_id);
    }

    public Person get_person_for_selected_loan() {
        Loan loan = get_selected();
        return loanController.getPerson(loan.getId());
    }

    public DVD get_dvd_for_selected_loan() {
        Loan loan = get_selected();
        return loanController.getDvd(loan.getId());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        loan_table = new javax.swing.JTable();
        filter_field = new javax.swing.JTextField();
        filter_label = new javax.swing.JLabel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getResourceMap(LoanListUI.class);
        setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("Form.border.title"))); // NOI18N
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        loan_table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Name/Title", "State", "Name", "Title", "copy_id"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Long.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        loan_table.setName("loan_table"); // NOI18N
        loan_table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        loan_table.getTableHeader().setReorderingAllowed(false);
        loan_table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                loan_tableMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(loan_table);

        filter_field.setText(resourceMap.getString("filter_field.text")); // NOI18N
        filter_field.setName("filter_field"); // NOI18N

        filter_label.setText(resourceMap.getString("filter_label.text")); // NOI18N
        filter_label.setName("filter_label"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(filter_label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(filter_field, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filter_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filter_label))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void loan_tableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loan_tableMousePressed
        parent.subselection_changed();
    }//GEN-LAST:event_loan_tableMousePressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField filter_field;
    private javax.swing.JLabel filter_label;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable loan_table;
    // End of variables declaration//GEN-END:variables
}
